//
//  CNUserAccount.swift
//  Ccweibo
//
//  Created by 陈锦聪 on 16/3/22.
//  Copyright © 2016年 Coco. All rights reserved.
//

import UIKit

// 对象归档需遵守NSCoding
class CNUserAccount: NSObject, NSCoding {
    /// 授权令牌
    var access_token: String?
    // 基本数据类型作为属性不能定义为可选,需赋初始值
    var expires_in: NSTimeInterval = 0 {
        didSet {
            expiresDate = NSDate(timeIntervalSinceNow: expires_in)
        }
    }
    /// 过期时间
    var expiresDate: NSDate?
    /// 用户信息id
    var uid: String?
    
    /// 用户昵称
    var screen_name: String?
    /// 用户头像
    var avatar_large: String?
    
    init(dict: [String: AnyObject]) {
        // 在super.init()之后给属性赋值,需定义为可选
        super.init()
        
        setValuesForKeysWithDictionary(dict)
    }
    // 找不到字典中对应的属性
    override func setValue(value: AnyObject?, forUndefinedKey key: String) {
//        print("UndefinedKey:\(key)")
    }
    // 归档属性
    func encodeWithCoder(aCoder: NSCoder) {
        aCoder.encodeObject(access_token, forKey: "access_token")
        aCoder.encodeDouble(expires_in, forKey: "expires_in")
        aCoder.encodeObject(expiresDate, forKey: "expiresDate")
        aCoder.encodeObject(uid, forKey: "uid")
        aCoder.encodeObject(screen_name, forKey: "screen_name")
        aCoder.encodeObject(avatar_large, forKey: "avatar_large")
    }
    // 解档属性
    required init?(coder aDecoder: NSCoder) {
        super.init()
        access_token = aDecoder.decodeObjectForKey("access_token") as? String
        expires_in = aDecoder.decodeDoubleForKey("expires_in")
        expiresDate = aDecoder.decodeObjectForKey("expiresDate") as? NSDate
        uid = aDecoder.decodeObjectForKey("uid") as? String
        screen_name = aDecoder.decodeObjectForKey("screen_name") as? String
        avatar_large = aDecoder.decodeObjectForKey("avatar_large") as? String
    }
    
    // 打印对象
    override var description: String {
        // 只读属性,get可以省略
        get {
            let keys = ["access_token", "expires_in", "expiresDate", "uid"]
            return "\n\tUserAccount: \(dictionaryWithValuesForKeys(keys).description)"
        }
    }

}
